package org.example.servlet;


import org.example.javabean.User;
import org.example.service.LoginService;
import org.example.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.sql.SQLException;

@WebServlet(name = "registerServlet", urlPatterns = "/register")
public class registerServlet extends HttpServlet {

    private UserService registerService = new UserService();

    protected void doGet(HttpServletRequest req,
                         HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    protected void doPost(HttpServletRequest req,
                          HttpServletResponse resp) throws ServletException, IOException {
        String reader=req.getParameter("reader");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String repassword=req.getParameter("repassword");
        String result=null;
        if (password != null && password.equals(repassword)) {
           User register = new User(username, password, reader);

            result = registerService.register(register);

            //注册成功：——>跳转至登录页面进行登录
            //注册失败：——>注册页面提示：注册失败
            if (result.equals("注册成功")) {
                // 注册
                resp.sendRedirect("/index.jsp?message=" + URLEncoder.encode(result, "utf-8"));
            } else {
                req.getRequestDispatcher("/register.jsp?message=" + result).forward(req, resp);

            }
        } else {
            req.getRequestDispatcher("/register.jsp?message=" +
                    "两次密码不一致").forward(req, resp);
        }
    }
}
